package com.demarc.pesquisas.infraestrutura.hibernate.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

import com.demarc.pesquisas.infraestrutura.util.enumeracao.IEnumeracaoComCharDescricao;

public class EnumCharUserType<E extends Enum<E>> implements UserType,
		ParameterizedType {

	private Class<E> clazz;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int[] sqlTypes() {
		return new int[] { Types.CHAR };
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Class<E> returnedClass() {
		return clazz;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object object1, Object object2)
			throws HibernateException {
		return object1 == object2 // NOPMD Need to compare the references
				|| (object1 != null && object2 != null && object1
						.equals(object2));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode(Object object) throws HibernateException {
		return object.hashCode();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void setParameterValues(Properties params) {
		String enumClassName = params.getProperty(HibernateTypes.ENUM_CLASS);
		if (enumClassName == null) {
			throw new MappingException("enumClassName parameter not specified");
		}
		try {
			this.clazz = (Class<E>) Class.forName(enumClassName);
		} catch (java.lang.ClassNotFoundException e) {
			throw new MappingException("enumClass " + enumClassName
					+ " not found", e);
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object assemble(Serializable cache, Object owner)
			throws HibernateException {
		return cache;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isMutable() {
		return false;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object nullSafeGet(ResultSet rs, String[] names,
			SessionImplementor session, Object owner)
			throws HibernateException, SQLException {
		IEnumeracaoComCharDescricao enumObject = null;

		String code = rs.getString(names[0]);

		if (!rs.wasNull()) {
			enumObject = getEnum(code.charAt(0));
		}
		return enumObject;
	}

	private IEnumeracaoComCharDescricao getEnum(char code) {
		Class<? extends Enum<E>> enumClass = returnedClass();
		Enum<E>[] enums = enumClass.getEnumConstants();
		for (int i = 0; i < enums.length; i++) {
			if (((IEnumeracaoComCharDescricao) enums[i]).getCodigo() == code) {
				return (IEnumeracaoComCharDescricao) enums[i];
			}
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void nullSafeSet(PreparedStatement pstm, Object value, int index,
			SessionImplementor session) throws HibernateException, SQLException {
		if (value == null) {
			pstm.setNull(index, Types.CHAR);
		} else {
			char enumCode;

			if (value instanceof IEnumeracaoComCharDescricao) {
				enumCode = ((IEnumeracaoComCharDescricao) value).getCodigo();
			} else {
				enumCode = ((Character) value).charValue();
			}
			pstm.setString(index, String.valueOf(enumCode));
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return original;
	}
}